<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/21
 * Time: 下午9:20
 */

namespace common\logic;


use common\models\BaseRegionModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class RegionLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return BaseRegionModel::find();
    }

    /**
     * @param $id
     *
     * @return array|null|BaseRegionModel
     */
    public function getById($id){
        return $this->_get(['id' => $id]);
    }

    public function getAll()
    {
        return $this->_all();
    }

    public function getFormatChild()
    {
        $regions = $this->getAll();

        return $this->getChild($regions,0);
    }

    /**
     * @param $parentId
     *
     * @return array|BaseRegionModel[]
     */
    public function getChildCity($parentId){
        return $this->_all(['parent'=>$parentId]);
    }

    /**
     * @param BaseRegionModel[] $regions
     * @param int               $parentId
     * @return array
     */
    protected function getChild($regions, $parentId)
    {
        $data = [];

        if(!empty($regions)) {
            foreach ($regions as $k => $region) {
                if($region->parent == $parentId){
                    unset($regions[$k]);
                    $d = $region->toArray(['id','region_name']);
                    $child = $this->getChild($regions,$region->id);
                    if(!empty($child)) {
                        $d['child'] = $child;
                    }
                    $data[] = $d;
                }
            }
        }
        return $data;
    }


    /**
     * @param $id
     *
     * @return array|BaseRegionModel
     */
    public function getParent($id)
    {
        //上海楼盘
        $query = $this->_getActiveQuery();
        return $query->select(['c.region_name','c.id'])->alias('b')->leftJoin('ph_base_region c','b.parent=c.id')->limit(1)->where(['b.id'=>$id])->one();
    }
}